//
//  ApiTableCell.swift
//  MockServer
//
//  Created by ethan on 16/10/31.
//  Copyright © 2016年 ethan. All rights reserved.
//

import Cocoa

protocol ApiTableCellProtocol: class {
    func viewDetail(api: Api, row: Int)
    func apiUpdated(api: Api, row: Int)
}

class ApiTableCell: NSTableCellView {
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }

    @IBOutlet weak var viewBtn: NSButton!
    @IBOutlet weak var apiTextField: NSTextField!
    
    var row: Int?

    var api: Api? {
        didSet {
            guard let address = api?.address else {
                return
            }
            apiTextField.stringValue = address
            
            apiTextField.delegate = self
        }
    }
    weak var detailHandler: ApiTableCellProtocol?
    
    @IBAction func responseToDetailBtn(_ sender: NSButton) {
        guard let api = api, let row = row else {
            return
        }
        
        detailHandler?.viewDetail(api: api, row: row)
    }
}

extension ApiTableCell: NSTextFieldDelegate {
    func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
        
        return true
    }
    
    override func controlTextDidChange(_ obj: Notification) {
        let address = apiTextField.stringValue
        guard var api = api, let row = row else {
            return
        }
        
        api.address = address
        detailHandler?.apiUpdated(api: api, row: row)
    }
}
